import java.util.ArrayList;
import java.util.List;

public class Solution {
    public boolean isCompleteTree(TreeNode root) {
        if (root == null) {
            return true;
        }
        List<ANode> nodes = new ArrayList<>();
        nodes.add(new ANode(root, 1));
        int i = 0;
        while (i < nodes.size()) {
            ANode anode = nodes.get(i++);
            if (anode.node != null) {
                nodes.add(new ANode(anode.node.left, anode.code * 2));
                nodes.add(new ANode(anode.node.right, anode.code * 2 + 1));
            }
        }

        // 检查最后一个非空节点的编码是否等于列表的大小
        for (int j = 0; j < nodes.size(); j++) {
            if (nodes.get(j).node == null) {
                // 如果发现空节点，后续所有节点都必须是空节点
                for (int k = j + 1; k < nodes.size(); k++) {
                    if (nodes.get(k).node != null) {
                        return false;
                    }
                }
                break;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        // 创建一个完全二叉树
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);

        Solution solution = new Solution();
        System.out.println(solution.isCompleteTree(root)); // 应该输出 true
    }
}

class ANode {  // Annotated Node
    TreeNode node;
    int code;

    ANode(TreeNode node, int code) {
        this.node = node;
        this.code = code;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}